package com.copa.gameStore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.copa.gameStore.domain.GameNews;
import com.copa.gameStore.mapper.GameNewsMapper;
import com.copa.gameStore.service.GameNewsService;
import com.copa.gameStore.utils.GameTimeUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author copa
 * @createDate 2022-09-25 21:35
 * @function
 */
@Service
public class GameNewsServiceImpl implements GameNewsService {

    private final static Integer YEAR = 3;

    @Resource
    private GameNewsMapper gameNewsMapper;

    @Resource
    private GameTimeUtils gameTimeUtils;

    @Override
    public void add() {
        // 假设就搜索这三年的，今年为第二年
        for (int i = 0; i < YEAR; i++) {
            String year = String.valueOf(Integer.valueOf(LocalDate.now().getYear() - 1 + i));
            String month = "";
            for (int j = 1; j <= 12; j++) {
                month = j < 10 ? "0" + j : String.valueOf(j);
                List<GameNews> gameInfoList = gameTimeUtils.getGamesInfo(year, month);
                if (Objects.nonNull(gameInfoList)) {
                    gameInfoList.forEach(gameNews -> {
                        QueryWrapper<GameNews> wrapper = new QueryWrapper<GameNews>().eq("chi_name", gameNews.getChiName())
                                .eq("platform", gameNews.getPlatform())
                                .eq("sale_time",gameNews.getSaleTime());
                        if (gameNewsMapper.selectCount(wrapper) <= 0) {
                            gameNewsMapper.insert(gameNews);
                        }
                    });
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public List<GameNews> findBySaleTimeYear(Integer year) {
        return gameNewsMapper.selectBySaleTimeYear(year);
    }
}
